package com.baichuan.zntx.rules;

import com.baichuan.common.core.utils.DateUtils;
import com.baichuan.zntx.domain.Device;
import com.baichuan.zntx.domain.bo.MessageBo;
import com.baichuan.zntx.domain.vo.MessageVo;
import com.baichuan.zntx.service.IMessageService;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Rule;
import org.jeasy.rules.api.Facts;

import java.util.List;

/**
 * @author mazhanliang
 */
@Rule(name = "Low Battery Rule", description = "Triggers when the battery level is low")
public class LowBatteryRule {
    private Device device;
    private final IMessageService messageService;
    public LowBatteryRule(IMessageService messageService){
        this.messageService = messageService;
    }
    @Condition
    public boolean isLowBattery(Facts facts) {
        device = facts.get("device");
        return device.getEnergy() < device.getEnergyAlert();
    }

    @Action
    public void triggerLowBatteryAlarm() {
        //插入低电量报警记录
        MessageBo messageBo = new MessageBo();
        messageBo.setStatus(-1);
        messageBo.setDeviceId(device.getId());
        messageBo.setType(0);
        List<MessageVo> messageVoList = messageService.queryList(messageBo);
        if(messageVoList==null || messageVoList.isEmpty()){
            messageBo.setContent("电量报警:" + device.getDeviceId() + ",电量为" + device.getEnergy());
            messageBo.setSendTime(DateUtils.getNowDate());
            messageBo.setSendCount(0);
            messageService.insertByBo(messageBo);
        }
    }
}
